package com.ruoyi.web.controller.backstage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.config.CrontabConfig;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.stylesheets.LinkStyle;

import javax.annotation.Resource;
import javax.validation.constraints.Null;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.constant.Constants.*;
import static com.ruoyi.common.utils.DateUtils.parseDate;


/**
 * @author Administrator
 */
@RequestMapping("/esb")
@RestController
public class EsbController extends BaseController {


    @Resource
    private IUserInfoBpmService iUserInfoBpmService;

    @Resource
    private IUserInfoLkService iUserInfoLkService;

    @Resource
    private IUserInfoEcService iUserInfoEcService;

    @Resource
    private IWorkItemPendService iWorkItemPendService;

    @Resource
    private ISyncSysUserService iSyncSysUserService;

    @Resource
    private ISyncSysDeptService iSyncSysDeptService;

    @Resource
    private ISysNoticeService iSysNoticeService;

    @Resource
    private ISysFileInfoService sysFileInfoService;

    @Resource
    private ISysProcessTypeService sysProcessTypeService;

    @Resource
    private IWorkItemOaService iWorkItemOaService;

    @Resource
    private CrontabConfig crontabConfig;

    /**
     * 获取待办待阅信息
     *
     * @param json 入参
     * @return  出参
     */
    @RequestMapping("/pend/getPending")
    @ResponseBody
    public JSONObject getPending(@RequestBody String json) {
        logger.info("获取待办待阅信息参数值： {}", json);
        JSONObject pendResult = new JSONObject();
        JSONObject jsonObject = JSON.parseObject(json);
        Object systemNameObj = jsonObject.get("systemName");
        Object procedureNoObj = jsonObject.get("procedureNo");
        Object procedureNameObj = jsonObject.get("procedureName");
        if(procedureNoObj==null||procedureNameObj==null){
            pendResult.put("code", HttpStatus.ERROR);
            pendResult.put("message","参数格式错误");
            logger.error("待办的ESB缺少流程code");
            return pendResult;
        }
        if (systemNameObj==null){
            pendResult.put("code", HttpStatus.ERROR);
            pendResult.put("message","参数格式错误");
            logger.error("待办的ESB缺少操作参数标志flag");
            return pendResult;
        }
        String systemName = systemNameObj.toString();
        String procedureNo = procedureNoObj.toString();
        String procedureName = procedureNameObj.toString();
        Map<String,Object> map;
        try {
            map = jsonToMap(json);
        } catch (Exception e) {
            pendResult.put("code", HttpStatus.ERROR);
            pendResult.put("message", "入参错误");
            logger.error("{}待办的ESB入参转换异常 :   {}", systemName,e.getMessage());
            return pendResult;
        }

        switch (systemName){
            case SYSTEM_EC:
            case SYSTEM_BPM:
            case SYSTEM_Portal:
                logger.info("{}待办的ESB同步开始",systemName);
                int bpmNum = iWorkItemPendService.insertOrUpdateWorkItemPendBpm(map);
                pendResult.put("code",bpmNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
                pendResult.put("message",bpmNum > 0 ? "success" : "失败");
                break;
            case SYSTEM_HR:
                int num = iWorkItemPendService.insertHrWorkItemPend(map);
                pendResult.put("code",num > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
                pendResult.put("message",num > 0 ? "success" : "失败");
                break;
            case SYSTEM_OA:
                int oaNum = iWorkItemPendService.insertOrUpdateWorkItemPendCommon(map);
                pendResult.put("code",oaNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
                pendResult.put("message",oaNum > 0 ? "success" : "失败");
                break;
            default:
                int insertNum = iWorkItemPendService.insertWorkItemPend(map);
                pendResult.put("code",insertNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
                pendResult.put("message",insertNum > 0 ? "success" : "失败");
        }
        SysProcessType sysProcessType = new SysProcessType();
        sysProcessType.setProcessNo(procedureNo);
        List<SysProcessType> sysProcessTypes = sysProcessTypeService.selectSysProcessTypeList(sysProcessType);
        if(sysProcessTypes!=null && sysProcessTypes.size()==0){
            sysProcessType.setProcessName(procedureName);
            sysProcessType.setStatus("0");
            sysProcessTypeService.insertSysProcessType(sysProcessType);
        }else {
            sysProcessType.setProcessName(procedureName);
            sysProcessTypeService.updateSysProcessTypeByNo(sysProcessType);
        }
        return pendResult;
    }

    /***
     * 获取更新待办待阅信息
     * @param json 入参
     * @return 出参
     */
    @RequestMapping("/pend/updatePended")
    @ResponseBody
    public JSONObject updatePended(@RequestBody String json) {
        logger.info("获取更新待办待阅信息参数值： {}", json);
        JSONObject pendedResult = new JSONObject();
        JSONObject jsonObject = JSON.parseObject(json);
        Object systemName = jsonObject.get("systemName");
        Object pendType = jsonObject.get("pendType");
        Object sequenceNo = jsonObject.get("sequenceNo");
        Object receiverUserCode = jsonObject.get("receiverUserCode");
        Object status = jsonObject.get("status");
        if(systemName==null){
            logger.info("ESB更新待办待阅信息,系统来源为空");
            pendedResult.put("code", HttpStatus.ERROR);
            pendedResult.put("message", "系统来源为空");
            return pendedResult;
        }
        if(pendType==null){
            logger.info("{}的ESB更新待办待阅信息--待办待阅标记参数为空",systemName);
            pendedResult.put("code", HttpStatus.ERROR);
            pendedResult.put("message", "待办待阅标记参数为空");
            return pendedResult;
        }
        if (sequenceNo==null){
            logger.info("{}的ESB更新待办待阅信息--待办待阅流程ID参数为空",systemName);
            pendedResult.put("code", HttpStatus.ERROR);
            pendedResult.put("message", "待办待阅流程ID参数为空");
            return pendedResult;
        }
        if (receiverUserCode==null){
            logger.info("{}的ESB更新待办待阅信息--待办待阅流程处理人参数为空",systemName);
            pendedResult.put("code", HttpStatus.ERROR);
            pendedResult.put("message", "待办待阅流程处理人参数为空");
            return pendedResult;
        }
        if (status==null){
            logger.info("{}的ESB更新待办待阅信息--待办待阅流程处理状态参数为空",systemName);
            pendedResult.put("code", HttpStatus.ERROR);
            pendedResult.put("message", "待办待阅流程处理状态参数为空");
            return pendedResult;
        }
        WorkItemPend workItemPend = new WorkItemPend();
        workItemPend.setSystemName(systemName.toString());
        workItemPend.setPendType(pendType.toString());
        workItemPend.setSequenceNo(sequenceNo.toString());
        workItemPend.setReceiverUserCode(receiverUserCode.toString());
        workItemPend.setStatus(status.toString());
        int insertNum = iWorkItemPendService.updateWorkItemPendStatus(workItemPend);
        if (SYSTEM_OA.equals(workItemPend.getSystemName())){
            WorkItemOa workItemOa = new WorkItemOa();
            workItemOa.setSequenceNo(workItemPend.getSequenceNo());
            workItemOa.setStatus(status.toString());
            iWorkItemOaService.updateWorkItemOaStatus(workItemOa);
        }

        if (insertNum > 0) {
            pendedResult.put("code", HttpStatus.SUCCESS);
            pendedResult.put("message", "成功");
            logger.info("{}的ESB更新待办待阅信息--更新成功",systemName);
        } else {
            pendedResult.put("code", HttpStatus.ERROR);
            pendedResult.put("message", "失败");
            logger.info("{}的ESB更新待办待阅信息--更新失败",systemName);
        }
        return pendedResult;
    }




    /**
     * LK系统的ESB用户信息同步
     * @param json 入参
     * @return 出参
     */
    @PostMapping("/userInfo/lk")
    @ResponseBody
    public JSONObject lkUserInfo(@RequestBody String json) {
        logger.info("领款用户信息入参： {}", json);
        JSONObject lkResult = new JSONObject();
        Map<String,Object> map;
        try {
            map = jsonToMap(json);
        } catch (Exception e) {
            lkResult.put("code", HttpStatus.ERROR);
            lkResult.put("message","入参错误");
            logger.error("领款的ESB同步用户信息入参转换异常 :   {}",e.getMessage());
            return lkResult;
        }

        Object flagObj = map.get("flag");
        if (flagObj==null){
            lkResult.put("code", HttpStatus.ERROR);
            lkResult.put("message","参数格式错误");
            logger.error("领款的ESB同步用户信息缺少操作参数标志flag");
            return lkResult;
        }
        String flag = (String)flagObj ;
        switch (flag){
            case "1":
                logger.info("新增领款用户信息");
                int insertNum = iUserInfoLkService.insertUserInfoLk(map);
                lkResult.put("code", insertNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
                lkResult.put("message",insertNum > 0 ? "success" : "失败");
                break;
            case "2":
            case "3":
                logger.info("修改领款用户信息");
                int updateNum = iUserInfoLkService.updateUserInfoLk(map);
                lkResult.put("code",updateNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
                lkResult.put("message",updateNum > 0 ? "success" : "失败");
                break;
            default:
                lkResult.put("code", HttpStatus.ERROR);
                lkResult.put("message","参数flag状态未知");
                logger.error("领款的ESB同步用户信息操作参数标志flag值,未定义");
        }
        return lkResult;
    }



    /**
     *  BPM系统的ESB用户信息同步
     * @param json  入参
     * @return 出参
     */
    @PostMapping("/userInfo/bpm")
    @ResponseBody
    public JSONObject bpmUserInfo(@RequestBody String json) {
        logger.info("BPM用户信息入参： {}", json);
        JSONObject bpmResult = new JSONObject();
        Map<String,Object> map;
        try {
            map = jsonToMap(json);
        } catch (Exception e) {
            bpmResult.put("code", HttpStatus.ERROR);
            bpmResult.put("message","入参错误");
            logger.error("BPM的ESB同步用户信息入参转换异常 :   {}",e.getMessage());
            return bpmResult;
        }

        Object flagObj = map.get("flag");
        if (flagObj==null){
            bpmResult.put("code", HttpStatus.ERROR);
            bpmResult.put("message","入参错误");
            logger.error("BPM的ESB同步用户信息缺少操作参数标志flag");
            return bpmResult;
        }
        String flag = (String)flagObj ;
        switch (flag){
            case "1":
                logger.info("新增BPM用户信息");
                int insertNum = iUserInfoBpmService.insertUserInfoBpm(map);
                bpmResult.put("code", insertNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
                bpmResult.put("message",insertNum > 0 ? "success" : "失败");
                break;
            case "2":
            case "3":
                logger.info("修改BPM用户信息");
                int updateNum = iUserInfoBpmService.updateUserInfoBpm(map);
                bpmResult.put("code",updateNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
                bpmResult.put("message",updateNum > 0 ? "success" : "失败");
                break;
            default:
                bpmResult.put("code", HttpStatus.ERROR);
                bpmResult.put("message","参数flag状态未知");
                logger.error("BPM的ESB同步用户信息操作参数标志flag值,未定义");
        }
        return bpmResult;
    }


    /**
     * BPM系统的ESB用户信息同步
     * @param json 入参
     * @return 出参
     */
    @PostMapping("userInfo/ec")
    @ResponseBody
    public JSONObject ecUserInfo(@RequestBody String json) {
        logger.info("EC用户信息入参： {}", json);
        JSONObject ecResult = new JSONObject();
        Map<String,Object> map;
        try {
            map = jsonToMap(json);
        } catch (Exception e) {
            // EC入参转换失败
            ecResult.put("code", HttpStatus.ERROR);
            ecResult.put("message","入参错误");
            logger.error("EC的ESB同步用户信息入参转换异常 :   {}",e.getMessage());
            return ecResult;
        }

        Object flagObj = map.get("flag");
        if (flagObj==null){
            ecResult.put("code", HttpStatus.ERROR);
            ecResult.put("message","入参错误");
            logger.error("EC的ESB同步用户信息缺少操作参数标志flag");
            return ecResult;
        }
        String flag = (String)flagObj ;
        switch (flag){
            case "1":
                logger.info("新增EC用户信息");
                int insertNum = iUserInfoEcService.insertUserInfoEc(map);
                ecResult.put("code", insertNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
                ecResult.put("message",insertNum > 0 ? "success" : "失败");
                break;
            case "2":
            case "3":
                logger.info("修改EC用户信息");
                int updateNum = iUserInfoEcService.updateUserInfoEc(map);
                ecResult.put("code",updateNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
                ecResult.put("message",updateNum > 0 ? "success" : "失败");
                break;
            default:
                ecResult.put("code", HttpStatus.ERROR);
                ecResult.put("message","参数flag状态未知");
                logger.error("EC的ESB同步用户信息操作参数标志flag值,未定义");
        }
        return ecResult;
    }

    /**
     * HR的ESB人员同步接口
     * @param json 入参
     * @return 出参
     */
    @PostMapping(value = "userInfo/syncOrgUser")
    public JSONObject syncOrgUser(@RequestBody String json) {
        logger.info("人员数据同步接口-—json ： {}", json);
        JSONObject result = new JSONObject();
        JSONObject jsonObject = JSON.parseObject(json);
        Object flagObj = jsonObject.get("flag");
        Object dataObj = jsonObject.get("data");
        String dataStr = JSON.toJSONString(dataObj);
        JSONObject dataStrObject = JSON.parseObject(dataStr);
        Object empIdObj = dataStrObject.get("emp_id");
        if (flagObj== null || dataObj==null ||empIdObj==null){
            result.put("code", HttpStatus.ERROR);
            result.put("message","入参错误");
            logger.error("人员数据同步ESB用户信息缺少操作参数标志flag");
            return result;
        }
        Object data = jsonObject.get("data");
        Map<String, Object> map;
        try {
            map = jsonToMap(data.toString());
        } catch (Exception e) {
            // 入参转换失败
            result.put("code", HttpStatus.ERROR);
            result.put("message", "入参错误");
            logger.error("人员数据同步ESB入参转换异常 :   {}", e.getMessage());
            return result;
        }

        String flag = (String) flagObj;
        map.put("flag", flag);
        String empId = (String) empIdObj;

        int i = iSyncSysUserService.existSyncSysUser(empId);
        if (i > 0) {
            logger.info("人员数据同步ESB修改,flag : {}", flag);
            int updateNum = iSyncSysUserService.updateSyncSysUser(map);
            result.put("code", updateNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
            result.put("message", updateNum > 0 ? "success" : "失败");
        } else {
            logger.info("人员数据同步ESB新增,flag : {}", flag);
            int InsertNum = iSyncSysUserService.insertSyncSysUser(map);
            result.put("code", InsertNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
            result.put("message", InsertNum > 0 ? "success" : "失败");
        }
        SyncSysUser syncSysUser = new SyncSysUser();
        syncSysUser.setSyncFlag("0");
        syncSysUser.setEmpId(empId);
        crontabConfig.syncUser(syncSysUser);
        return result;
    }

    @PostMapping("userInfo/syncOrgUnit")
    public JSONObject syncOrgUnit(@RequestBody String json) {
        logger.info("组织数据同步接口-—json ： {}",  json);
        JSONObject result = new JSONObject();
        JSONObject jsonObject = JSON.parseObject(json);
        Object flagObj = jsonObject.get("flag");
        if (flagObj==null){
            result.put("code", HttpStatus.ERROR);
            result.put("message","入参错误");
            logger.error("ESB组织数据同步接口--缺少操作参数标志flag");
            return result;
        }
        Object data = jsonObject.get("data");
        Map<String, Object> map;
        try {
            map = jsonToMap(data.toString());
        } catch (Exception e) {
            // 入参转换失败
            result.put("code", HttpStatus.ERROR);
            result.put("message", "入参错误");
            logger.error("组织数据同步接口ESB入参转换异常 :   {}", e.getMessage());
            return result;
        }
        Object deptIdCodeObj = map.get("dept_idcode");
        if (deptIdCodeObj==null){
            result.put("code", HttpStatus.ERROR);
            result.put("message","入参错误");
            logger.error("ESB组织数据同步接口--缺少部门id");
            return result;
        }
        String flag = (String)flagObj ;
        String deptIdCode = (String)deptIdCodeObj ;
        map.put("flag",flag);
        int i = iSyncSysDeptService.existSyncSysDept(deptIdCode);
        if (i > 0) {
            logger.info("ESB组织数据同步接口--修改,flag:{}", flag);
            int updateNum = iSyncSysDeptService.updateSyncSysDept(map);
            result.put("code", updateNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
            result.put("message", updateNum > 0 ? "success" : "失败");
        } else {
            logger.info("ESB组织数据同步接口--新增,flag:{}", flag);
            int InsertNum = iSyncSysDeptService.insertSyncSysDept(map);
            result.put("code", InsertNum > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
            result.put("message", InsertNum > 0 ? "success" : "失败");
        }
        SyncSysDept syncSysDept = new SyncSysDept();
        syncSysDept.setSyncFlag("0");
        syncSysDept.setDeptIdCode(deptIdCode);
        crontabConfig.syncDept(syncSysDept);
        return result;
    }

    /**
     * HR的ESB部门同步接口
     * @param json 入参
     * @return 出参
     */
    @PostMapping("notice/syncNotice")
    public JSONObject syncNotice(@RequestBody String json) {
        logger.info("通知公告同步接口-—json ： {}",  json);
        JSONObject result = new JSONObject();
        Map<String,Object> map;
        try {
            map = jsonToMap(json);
        } catch (Exception e) {
            // 入参转换失败
            result.put("code", HttpStatus.ERROR);
            result.put("message",e.getMessage());
            logger.error("通知公告的ESB入参转换异常 :   {}",e.getMessage());
            return result;
        }
        List fileInfos = (ArrayList)map.get("fileInfo");
        List<String> fileIds = new ArrayList<>();
        if (fileInfos.size()>0){
            for (int i = 0; i <fileInfos.size() ; i++) {
                Object fileInfoObj = fileInfos.get(i);
                if (fileInfoObj!=null){
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(fileInfoObj));
                    Object filePath = jsonObject.get("filePath");
                    Object fileName = jsonObject.get("fileName");
                    Object fileSize = jsonObject.get("fileSize");
                    Object createTime = jsonObject.get("createTime");
                    SysFileInfo sysFileInfo = new SysFileInfo();
                    sysFileInfo.setFilePath(filePath == null ? null : filePath.toString());
                    sysFileInfo.setFileName(fileName == null ? null : fileName.toString());
                    sysFileInfo.setFileSize(fileSize == null ? null : fileSize.toString());
                    sysFileInfo.setCreateTime(createTime == null ? null : parseDate(createTime));
                    String fileId = sysFileInfoService.insertSysFileInfo(sysFileInfo);
                    fileIds.add(fileId);
                }
            }
        }
        map.remove("filePath");
        map.put("fileIds",JSON.toJSON(fileIds).toString());
        int i = iSysNoticeService.insertNotice(map);
        result.put("code",i > 0 ? HttpStatus.SUCCESS : HttpStatus.ERROR);
        result.put("message",i > 0 ? "success" : "失败");
        return result;
    }

    /**
     * 转换
     * @param json 入参
     * @return 出参
     * @throws Exception 异常
     */
    private Map<String,Object> jsonToMap (String json)throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(json, new TypeReference<Map<String, Object>>(){});
    }

}
